package com.ruoyi.web.controller.byw;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.BywProductResourcePack;
import com.ruoyi.system.domain.vo.ViteaNum;
import com.ruoyi.system.service.IBywProductResourcePackService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.BywUserVitaeInfo;
import com.ruoyi.system.service.IBywUserVitaeInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户资源包Controller
 * 
 * @author ruoyi
 * @date 2024-05-25
 */
@Api("客户管理")
@RestController
@RequestMapping("/byw/user-vitae-info")
public class BywUserVitaeInfoController extends BaseController
{
    @Autowired
    private IBywUserVitaeInfoService bywUserVitaeInfoService;

    @Autowired
    private IBywProductResourcePackService productResourcePackService;

    @Autowired
    private ISysUserService userService;

    @ApiOperation("客户查询列表")
    @PreAuthorize("@ss.hasPermi('byw:user-vitae-info:user-list')")
    @GetMapping("/user-list")
    public TableDataInfo userList(SysUser user)
    {
        startPage();
        user.setRoleId(100L);
        List<SysUser> list = userService.selectRoleAllocatedList(user);
        for (SysUser sysUser : list){
            ViteaNum viteaNum = bywUserVitaeInfoService.vitaeNum(sysUser.getUserId());
            sysUser.setViteaNum(viteaNum.getNum());
            sysUser.setResidueNum(viteaNum.getResidueNum());
        }
        return getDataTable(list);
    }

    @ApiOperation("新增客户")
    @PreAuthorize("@ss.hasPermi('byw:user:add-user')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add-user")
    public AjaxResult addUser(@Validated @RequestBody SysUser user)
    {
        Long[] roleIds = {100L};
        user.setRoleIds(roleIds);
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增客户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增客户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增客户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }



    /**
     * 修改用户
     */
    @ApiOperation("编辑客户")
    @PreAuthorize("@ss.hasPermi('byw:user:edit-user')")
    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/edit-user")
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        Long[] roleIds = {100L};
        user.setRoleIds(roleIds);
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user))
        {
            return error("修改客户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改客户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改客户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }


    /**
     * 查询用户资源包列表
     */
    @PreAuthorize("@ss.hasPermi('byw:user-vitae-info:list')")
    @GetMapping("/list")
    public TableDataInfo list(BywUserVitaeInfo bywUserVitaeInfo)
    {
        startPage();
        if (bywUserVitaeInfo.getSysUserId() == null){
            bywUserVitaeInfo.setSysUserId(getUserId());
        }
        List<BywUserVitaeInfo> list = bywUserVitaeInfoService.selectBywUserVitaeInfoList(bywUserVitaeInfo);
        return getDataTable(list);
    }

    /**
     * 导出用户资源包列表
     */
    @PreAuthorize("@ss.hasPermi('byw:user-vitae-info:export')")
    @Log(title = "用户资源包", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BywUserVitaeInfo bywUserVitaeInfo)
    {
        List<BywUserVitaeInfo> list = bywUserVitaeInfoService.selectBywUserVitaeInfoList(bywUserVitaeInfo);
        ExcelUtil<BywUserVitaeInfo> util = new ExcelUtil<BywUserVitaeInfo>(BywUserVitaeInfo.class);
        util.exportExcel(response, list, "用户资源包数据");
    }

    /**
     * 获取用户资源包详细信息
     */
    @PreAuthorize("@ss.hasPermi('byw:user-vitae-info:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bywUserVitaeInfoService.selectBywUserVitaeInfoById(id));
    }

    /**
     * 新增用户资源包
     */
    @PreAuthorize("@ss.hasPermi('byw:user-vitae-info:add')")
    @Log(title = "用户资源包", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BywUserVitaeInfo bywUserVitaeInfo)
    {
        return toAjax(bywUserVitaeInfoService.insertBywUserVitaeInfo(bywUserVitaeInfo));
    }

    /**
     * 分配用户资源包
     */
    @PreAuthorize("@ss.hasPermi('byw:user-vitae-info:distribution')")
    @Log(title = "分配用户资源包", businessType = BusinessType.OTHER)
    @PutMapping("/distribution/{sysUserId}/{productId}")
    public AjaxResult distribution(@PathVariable("sysUserId") Long sysUserId, @PathVariable("productId") Long productId)
    {
        BywProductResourcePack productResourcePack = productResourcePackService.selectBywProductResourcePackById(productId);
        if (productResourcePack == null){
            return error("要分配的产品不存在");
        }
        BywUserVitaeInfo userVitaeInfo = new BywUserVitaeInfo();
        userVitaeInfo.setSysUserId(sysUserId);
        userVitaeInfo.setViteaName(productResourcePack.getProductName());
        userVitaeInfo.setVitaeNum(productResourcePack.getVitaeNum());
        userVitaeInfo.setResidueNum(userVitaeInfo.getVitaeNum());
        userVitaeInfo.setCreateBy(getUsername());
        userVitaeInfo.setCreateTime(DateUtils.getNowDate());
        userVitaeInfo.setUpdateBy(userVitaeInfo.getCreateBy());
        userVitaeInfo.setUpdateTime(userVitaeInfo.getCreateTime());
        userVitaeInfo.setExpiryTime(new Date(getDayAfterEndTime(System.currentTimeMillis(), productResourcePack.getPeriodOfValidity())));
        int i = bywUserVitaeInfoService.insertBywUserVitaeInfo(userVitaeInfo);
        productResourcePack.setBoundState(1);
        productResourcePack.setUpdateBy(getUsername());
        productResourcePack.setUpdateTime(DateUtils.getNowDate());
        productResourcePackService.updateBywProductResourcePack(productResourcePack);
        return toAjax(i);
    }

    /**
     * 修改用户资源包
     */
    @PreAuthorize("@ss.hasPermi('byw:user-vitae-info:edit')")
    @Log(title = "用户资源包", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BywUserVitaeInfo bywUserVitaeInfo)
    {
        return toAjax(bywUserVitaeInfoService.updateBywUserVitaeInfo(bywUserVitaeInfo));
    }

    /**
     * 删除用户资源包
     */
    @PreAuthorize("@ss.hasPermi('byw:user-vitae-info:remove')")
    @Log(title = "用户资源包", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bywUserVitaeInfoService.deleteBywUserVitaeInfoByIds(ids));
    }

    public static long getDayAfterEndTime(long millis, int x) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(millis);
        // 将日期设置为昨天
        calendar.add(Calendar.DATE, x);

        // 设置为昨天的结束时间
        //calendar.set(Calendar.HOUR_OF_DAY, 23);
        //calendar.set(Calendar.MINUTE, 59);
        //calendar.set(Calendar.SECOND, 59);
        //calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTimeInMillis();
    }
}
